package com.isecta.maplew.utility;

import java.net.URLEncoder;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class NGFXMailRunner { 

    Folder inbox;
    private static Logger log = Logger.getLogger(NGFXMailRunner.class);

    public synchronized String readGmail(String email, String password) {
        StringBuilder links = new StringBuilder();
        links.append("<links>");
        String link = "";
        try {
            Properties props = System.getProperties();
            props.setProperty("mail.store.protocol", "imaps");

            /* Create the session and get the store for read the mail. */
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("imaps");
            store.connect("imap.gmail.com", email, password);

            /* Mention the folder name which you want to read. */
            inbox = store.getFolder("Inbox");
            int unReadMCount = inbox.getUnreadMessageCount();
            log.debug("No of Unread Messages : " + unReadMCount);
            if (unReadMCount == 0) {
                return links.append("</links>").toString();
            }
            /* Open the inbox using store. */
            //inbox.open(Folder.READ_ONLY);
            inbox.open(Folder.READ_WRITE);
            /* Get the messages which is unread in the Inbox */
            Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
            /* Use a suitable FetchProfile */
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.CONTENT_INFO);
            inbox.fetch(messages, fp);
            try {
                for (int i = 0; i < messages.length; i++) {
                    Message message = messages[i];
                    link = this.parseMessage(message);
                    links.append(link);
                }
                inbox.setFlags(messages, new Flags(Flags.Flag.SEEN), true);
                inbox.close(true);
                store.close();
            } catch (Throwable ex) {
                log.debug("readMail :: Exception arise at the time of read mail " + ex);
                ex.printStackTrace();
            }
        } catch (NoSuchProviderException ex) {
            log.debug("readMail :: Error on NoSuchProviderException " + ex);
            ex.printStackTrace();
        } catch (MessagingException ex) {
            log.debug("readMail :: Error on MessagingException " + ex);
            ex.printStackTrace();
        } catch (Throwable ex) {
            log.debug("readMail :: Error on MessagingException " + ex);
            ex.printStackTrace();
        }
        if (!link.isEmpty()) {
            links.append("<mailfound>").append("1").append("</mailfound>");
        } else {
            links.append("<mailfound>").append("0").append("</mailfound>");
        }
        links.append("</links>");
        return links.toString();
    }

    public String parseMessage(Message message) throws Exception {
        StringBuilder link = new StringBuilder();
        try {
            String sub = message.getSubject();
            if (!sub.contains("Action Required to Activate Membership for Forex")) {
                return "";
            }
            String contentType = message.getContentType();
            System.out.println("Content Type : " + contentType);
            if (message.getContent() instanceof Multipart) {
                Multipart mp = (Multipart) message.getContent();
            int count = mp.getCount();
            for (int j = 0; j < count; j++) {
                String s = mp.getBodyPart(j).getContent().toString();
                String lines[] = s.split("\\r?\\n");
                for (int k = 0; k < lines.length; k++) {
                    if (lines[k].contains("http://nigeria-forex.com/register.php") && lines[k].startsWith("http")) {
                        log.debug("readMail :: Posting link found " + lines[k]);
                        link.append("<link>").append(URLEncoder.encode(lines[k], "UTF-8")).append("</link>");
                        break;
                    }
                }
            }
            }else {
                String html = message.getContent().toString();
                org.jsoup.nodes.Document doc = Jsoup.parse(html);
                Elements links = doc.select("a[href]");
                for (Element linc : links) {
                    if (linc.text().contains("http://nigeria-forex.com/register.php")) {
                        log.debug("readMail :: Posting link found " + linc.text());
                        link.append("<link>").append(URLEncoder.encode(linc.text(), "UTF-8")).append("</link>");
                        break;
                    }

                }
            }
            
        } catch (Throwable ex) {
            log.debug("readAllMessages :: Error " + ex);
            ex.printStackTrace();
        }
        return link.toString();
    }
}